package com.sam.im.heiqun.uis.activities;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.sam.im.heiqun.R;
import com.sam.im.heiqun.entities.ImageEntity;
import com.sam.im.heiqun.entities.SendCircleEntivity;
import com.sam.im.heiqun.entities.VedioEntity;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.uis.adapters.AtHeadAdapter;
import com.sam.im.heiqun.uis.adapters.SendCircleAdapter;
import com.sam.im.heiqun.utils.BitmapUtils;
import com.sam.im.heiqun.utils.FileSaveUtil;
import com.sam.im.heiqun.utils.HttpAssist;
import com.sam.im.heiqun.utils.ImageCheckoutUtil;
import com.sam.im.heiqun.utils.ImageCompressUtil;
import com.sam.im.heiqun.utils.PersimmionsUtils;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.sam.im.heiqun.widgets.imagepicker.PhotoPickerActivity;
import com.sam.im.heiqun.widgets.imagepicker.SelectModel;
import com.sam.im.heiqun.widgets.imagepicker.intent.PhotoPickerIntent;
import com.yuyh.library.audiovideo.Utils;
import com.yuyh.library.audiovideo.VideoRecorderActivity;
import com.yuyh.library.nets.callbacks.AbsAPICallback;
import com.yuyh.library.nets.exceptions.ApiException;
import com.yuyh.library.uis.activitys.BaseSwipeBackActivity;
import com.yuyh.library.utils.GlideUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import com.sam.im.heiqun.utils.StringUtils;

public class SendCircleActivity extends BaseSwipeBackActivity {

    private static final int SDK_PERMISSION_REQUEST = 127;
    private static final int SMALL_VEDIO = 2131;
    private static final String TAG = "SendCircleActivity";

//    private int goSelectType = 0 ;//

    @BindView(R.id.pre_v_back)
    ImageView preVBack;
    @BindView(R.id.pre_tv_title)
    TextView preTvTitle;
    @BindView(R.id.ok)
    TextView ok;
    @BindView(R.id.content_et)
    EditText editText;

    @BindView(R.id.relative_address)
    RelativeLayout relative_address;
    @BindView(R.id.relative_all)
    RelativeLayout relative_all;
    @BindView(R.id.relative_at)
    RelativeLayout relative_at;
    @BindView(R.id.relative_video)
    RelativeLayout relative_video;
    @BindView(R.id.image_video)
    ImageView image_video;
    @BindView(R.id.recycler_view)
    RecyclerView recycler_view;
    @BindView(R.id.recycler_view_lw)
    RecyclerView recycler_view_lw;
    @BindView(R.id.txt_all_right)
    TextView txt_all_right;

    AtHeadAdapter mAtHeadAdapter ;
    AtHeadAdapter mAtHeadAdapterlw ;
    String[] atdatas ;
    String[] atdataslw ;
    String uids = "";
    String uheads = "";

    private List<Bitmap> photodatas = new ArrayList<Bitmap>();
    private GridView mGridView;
    private String photoPath;
    private SendCircleAdapter adapter;
    private static int CHOSE_PICS = 1111;
    private static final int IMAGE_SIZE = 300 * 1024;
    private File mCurrentPhotoFile;
    private List<File> files = new ArrayList<>();
    private ImageEntity upload;

    double lat = 0;//经度
    double lut = 0;//纬度
    private TextView txt_adr_content;
    String addr ="";
    String uidsall="";
    private int typeall = 0 ;

    String mvedioimgurl = "";//缩略图
    String mvediourl = "" ;

    private int type = 0 ;//0-图片；1-文字；2-小视频

    private int isSend = 0 ;
    private PersimmionsUtils persimmionsUtils ;
    public static void start(Activity activity, int type){
        Intent intent = new Intent(activity, SendCircleActivity.class);
        intent.putExtra("type", type);
        activity.startActivity(intent);
    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_send_circle;
    }

    @Override
    protected String getTitleText() {
        return null;
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        type = getIntent().getIntExtra("type",0);
        ok.setText("发布");
        ok.setVisibility(View.VISIBLE);
        txt_adr_content = (TextView) findViewById(R.id.txt_adr_content);
//        ok.setBackgroundResource(R.drawable.shape_sure_bt);
        // 设置默认图片为加号
        Bitmap bp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_addpic);
        photodatas.add(bp);
//        ToolsUtils.verifyStoragePermissions(SendCircleActivity.this);
        // 找到控件ID
        mGridView = (GridView) findViewById(R.id.gridView1);
        // 绑定Adapter
        adapter = new SendCircleAdapter(getApplicationContext(), photodatas, mGridView);
        mGridView.setAdapter(adapter);
        if (1 == type){
            mGridView.setVisibility(View.GONE);
        }
        // 设置点击监听事件
        mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (photodatas.size() == 10) {
                    Toast.makeText(SendCircleActivity.this, getResources().getString(R.string.image_man_9), Toast.LENGTH_SHORT).show();
                } else {
                    if (position == photodatas.size() - 1) {
                        isgo = false ;
                        getPersimmions();
                    } else {
                        ToolsUtils.showToast(SendCircleActivity.this,getResources().getString(R.string.long_an_delete));
                        //Toast.makeText(SendCircleActivity.this, "长按可选择删除", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
        // 设置长按事件
        mGridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                if (position!=0){//判断position不等于0是处理加号不能长按
                    dialog(position);
                }

                return true;
            }
        });
        initAtHead();
        initPersimmions();
    }

    private void initAtHead(){
        Log.i(TAG, "initAtHead: -----001-----");
        if (null==atdatas || atdatas.length <=0){
            recycler_view.setVisibility(View.GONE);
        }else {
            Log.i(TAG, "initAtHead: -----001-----atdatas.length="+atdatas.length);
            recycler_view.setVisibility(View.VISIBLE);
        }
        Log.i(TAG, "initAtHead: -----002-----");
//        if (null == mAtHeadAdapter || null == atdatas){
            mAtHeadAdapter = new AtHeadAdapter(SendCircleActivity.this,atdatas);
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
            linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
            linearLayoutManager.setStackFromEnd(false);
            recycler_view.setLayoutManager(linearLayoutManager);
            recycler_view.setAdapter(mAtHeadAdapter);
//        }else {
//            mAtHeadAdapter.notifyDataSetChanged();
//        }

    }
    private void initHeadlw(){
        Log.i(TAG, "initAtHead: -----001-----");
        if (null==atdataslw || atdataslw.length <=0){
            recycler_view_lw.setVisibility(View.GONE);
        }else {
            Log.i(TAG, "initAtHead: -----001-----atdatas.length="+atdataslw.length);
            recycler_view_lw.setVisibility(View.VISIBLE);
        }
        Log.i(TAG, "initAtHead: -----002-----");
//        if (null == mAtHeadAdapter || null == atdatas){
            mAtHeadAdapterlw = new AtHeadAdapter(SendCircleActivity.this,atdataslw);
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
            linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
            linearLayoutManager.setStackFromEnd(false);
        recycler_view_lw.setLayoutManager(linearLayoutManager);
        recycler_view_lw.setAdapter(mAtHeadAdapterlw);
//        }else {
//            mAtHeadAdapter.notifyDataSetChanged();
//        }

    }

    @TargetApi(23)
    protected void getPersimmions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> permissions = new ArrayList<String>();
            // 读写权限
            int pos = 0 ;
            if (addPermission(permissions, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                pos ++ ;
            }
            if (addPermission(permissions, Manifest.permission.CAMERA)){
                pos ++ ;
            }
            if (2==pos){
                gotoPhoto();
            }
            if (permissions.size() > 0) {
                Log.i(TAG, "getPersimmions: --------001--------");
                requestPermissions(permissions.toArray(new String[permissions.size()]), SDK_PERMISSION_REQUEST);
            }
        }else {
            gotoPhoto();
        }
    }

    @TargetApi(23)
    private boolean addPermission(ArrayList<String> permissionsList, String permission) {
        Log.i(TAG, "getPersimmions: --------002--------");
        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
            Log.i(TAG, "getPersimmions: --------003--------");
            if (shouldShowRequestPermissionRationale(permission)) {
                //拒绝了也是可以强行提示的，不过如果再也不提示的情况还没处理
                permissionsList.add(permission);
                Log.i(TAG, "getPersimmions: --------004--------");
                return false;
            } else {
                Log.i(TAG, "getPersimmions: --------005--------");
                permissionsList.add(permission);
                return false;
            }
        } else {
            Log.i(TAG, "getPersimmions: --------0011--------");
            return true;
        }
    }

    @TargetApi(23)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.i(TAG, "getPersimmions: --------006--------");
        switch (requestCode) {
            case SDK_PERMISSION_REQUEST:
                Log.i(TAG, "getPersimmions: --------007--------");
                Map<String, Integer> perms = new HashMap<String, Integer>();
                for (int i = 0; i < permissions.length; i++)
                    perms.put(permissions[i], grantResults[i]);
                Log.i(TAG, "getPersimmions: --------008--------");
                try {
                    int isgre = 0 ;
                    if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                        isgre ++;
                    }
                    if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                        isgre ++;
                    }
                    if (2 <= isgre){
                        gotoPhoto();
                    }else {
                        Toast.makeText(this, getResources().getString(R.string.disable_picture_permission_will_make_send_picture_unusable), Toast.LENGTH_SHORT)
                                .show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    boolean isgo = false ;

    private void gotoPhoto(){
        if (0 == type){//图片
            if (!isgo){
                PhotoPickerIntent photointent = new PhotoPickerIntent(SendCircleActivity.this);
                photointent.setSelectModel(SelectModel.MULTI);
                photointent.setShowCarema(true); // 是否显示拍照， 默认false
                photointent.setMaxTotal(9 - photodatas.size() + 1); // 最多选择照片数量，默认为9
                //photointent.setImageConfig(conFig);
                startActivityForResult(photointent, CHOSE_PICS);
            }
            isgo = true ;
        }else {
            persimmionsUtils.getPersimmions(4,new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO});
        }
    }


    /**
     * 初始化权限管理
     */
    private void initPersimmions() {
        persimmionsUtils = new PersimmionsUtils(SendCircleActivity.this, new PersimmionsUtils.PersimmionsListener() {
            @Override
            public void OnPersimmionsSuccess(int type) {
                switch (type) {
                    case 4:
                        // 录制
                        File saveDir = null;
                        saveDir = new File(FileSaveUtil.getSdCardPath()+"/easyVideo/","yunxin_"+System.currentTimeMillis());
                        saveDir.mkdirs();

//                        MaterialCamera materialCamera = new MaterialCamera(ChatBaseActivity.this)
//                                .saveDir(saveDir)
//                                .showPortraitWarning(true)
//                                .allowRetry(true)
//                                .defaultToFrontFacing(true)
//                                .allowRetry(true)
//                                .autoSubmit(false)
//                                .labelConfirm(R.string.mcam_use_video);
//                        materialCamera.start(SMALL_VEDIO, false);

                        VideoRecorderActivity.start(SendCircleActivity.this, saveDir, Utils.videoMaxTime, SMALL_VEDIO);

                        break;
                }

            }

            @Override
            public void OnPersimmionsFail(int type, int pos, String persimmion) {
                showToast(getResources().getString(R.string.no_pawr_nouse));
            }
        });
    }



    /*
     * Dialog对话框提示用户删除操作 position为删除图片位置
	 */
    protected void dialog(final int position) {
        if (position == photodatas.size()) {
            return;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(SendCircleActivity.this);
        builder.setMessage(getResources().getString(R.string.delete_image_ok));
        builder.setTitle(getResources().getString(R.string.tip));
        builder.setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                try {
                    photodatas.remove(position);
                    files.remove(position);
                }catch (Exception e){
                    e.printStackTrace();
                }
                adapter.notifyDataSetChanged();
            }
        });
        builder.setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    // 响应startActivityForResult，获取图片路径
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 0x1 && resultCode == RESULT_OK) {
            if (data != null) {
                ContentResolver resolver = getContentResolver();
                try {
                    Uri uri = data.getData();
                    // 这里开始的第二部分，获取图片的路径：
                    String[] proj = {MediaStore.Images.Media.DATA};
                    Cursor cursor = managedQuery(uri, proj, null, null, null);
                    // 按我个人理解 这个是获得用户选择的图片的索引值
                    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    cursor.moveToFirst();
                    // 最后根据索引值获取图片路径
                    photoPath = cursor.getString(column_index);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else if (requestCode == CHOSE_PICS) {
            if (data != null) {
                ArrayList<String> stringArrayListExtra = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);
                if (stringArrayListExtra.size() > 0) {
                    for (int i = 0; i < stringArrayListExtra.size(); i++) {
                        String imgpath = stringArrayListExtra.get(i);
                        Log.i("info","选择的图片路劲=="+imgpath);
                        try {
//              Bitmap bitmap = PictureUtil.getBitmapFormUri(this, uri);
                           /* Bitmap bitmap = PictureUtil.getSmallBitmap(imgpath);
                            if (bitmap == null) {
                                assert imgpath != null;
                                mCurrentPhotoFile = new File(imgpath); // 图片文件路径
                            } else {
                                mCurrentPhotoFile = PictureUtil.bitmapToFileJPG(bitmap, imgpath);
                            }*/
                            File getfile = new File(imgpath);
                           // mCurrentPhotoFile = new File(imgpath);
                           // assert mCurrentPhotoFile != null;
                            if (getfile.exists()) {
                                int size = ImageCheckoutUtil.getImageSize(ImageCheckoutUtil.getLoacalBitmap(imgpath));
                                float s = size / 8.0f / 1024;
                                if (s > IMAGE_SIZE) {
                                    Log.i("info", "图片尺寸太大");
                                } else {//这里处理返回的路径
                                    files.add(ImageCompressUtil.changeImage(getfile,SendCircleActivity.this));
                                    //sendImage(mCurrentPhotoFile);
                                    Bitmap newBp = BitmapUtils.decodeSampledBitmapFromFd(getfile.getPath(), 300, 300);
                                    photodatas.remove(photodatas.size() - 1);
                                    Bitmap bp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_addpic);
                                    photodatas.add(newBp);
                                    photodatas.add(bp);
                                    adapter.notifyDataSetChanged();
                                }
                            } else {
                                showToast(getResources().getString(R.string.this_file_nonentity));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        //files.add(new File(imgpath));

                    }
                }
            }
            // Uri uri = data.getData();
            // String path = FileSaveUtil.getPath(getApplicationContext(), uri);
        }else if (requestCode == SelecteGroupFriendActivity.SELECT_FRIEND_IDS_FOR_RESULT){

            if (resultCode == RESULT_OK){
                uids = data.getStringExtra("uids");
                uheads = data.getStringExtra("uheads");
                Log.i(TAG, "onActivityResult: -------------uids="+uids);
                Log.i(TAG, "onActivityResult: -------------uheads="+uheads);
                if (null!=uheads)atdatas = uheads.split(",");
                initAtHead();
            }

        }else if (requestCode == ChatActivity.RESULT_LOCATION){
            if (resultCode == 11) {
                String city = data.getStringExtra("city");//城市
                String pro = data.getStringExtra("pro");//省
                String des = data.getStringExtra("des");//描述
                String district = data.getStringExtra("dis");//区
                String street = data.getStringExtra("ste");//街道
                String streetNum = data.getStringExtra("stenum");//街道号
                String pic = data.getStringExtra("pic");//图片
                String poi = data.getStringExtra("poi");//详细
                lat = data.getDoubleExtra("lat", 0);//经度
                lut = data.getDoubleExtra("lut", 0);//纬度
                Log.i("info", "地图截屏成功开始发送" + pic);
//                File file = new File(pic);
                StringBuffer strb = new StringBuffer("");
                if (!district.equals("")) {
                    strb.append(district);
                }
                if (!street.equals("")) {
                    strb.append(street);
                }
                if (!streetNum.equals("")) {
                    strb.append(streetNum);
                }
                if (!poi.equals("")) {
                    strb.append(poi);
                }
                addr = strb.toString();
//                sendLocation(file, addr, lat, lut);

                txt_adr_content.setText(addr);

            }
        }else if (requestCode == CircleLookWhoActivity.SELECT_LLOK_WHO_FOR_RESULT){
            if (resultCode == 10){
                int type = data.getIntExtra("type",0);
                switch (type){
                    case 1:
                        typeall = 0 ;
                        txt_all_right.setText(getResources().getString(R.string.circle_public));
                        break;
                    case 2:
                        typeall = 1 ;
                        txt_all_right.setText(getResources().getString(R.string.circle_private));
                        break;
                    case 3:
                        typeall = 2 ;
                        txt_all_right.setText(getResources().getString(R.string.circle_bufen));
                        break;
                    case 4:
                        typeall = 3 ;
                        txt_all_right.setText(getResources().getString(R.string.circle_nolook));
                        break;
                }
                uidsall = data.getStringExtra("uids");
                String muheads = data.getStringExtra("uheads");
                if (null!=muheads)atdataslw = muheads.split(",");
                initHeadlw();
            }
        }else if (requestCode == SMALL_VEDIO){
//            case 2131://
                if (resultCode == RESULT_OK)
                    try {
                        String filePath = data.getStringExtra("videoUrl");
                        Log.e("lzf_video", filePath);
                        if (filePath != null && !filePath.equals("")) {
                            if (filePath.startsWith("file://")) {
                                filePath = data.getStringExtra("videoUrl").substring(7, filePath.length());
                            }
                            int duration= 0 ;
                            Log.i("info", "视频保存在：" + filePath);
                            //String[] split = filePath.split("/");
                            MediaMetadataRetriever media = new MediaMetadataRetriever();
                            media.setDataSource(filePath);
                            Bitmap bitmap = media.getFrameAtTime();
                            filePath.substring(0, filePath.lastIndexOf("/"));
                            String imgname = System.currentTimeMillis() + ".jpg";
                              /*  String urlpath = Environment
                                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/easyimVideo/" + imgname;*/
                            String urlpath = Environment.getExternalStorageDirectory() + "/" + imgname;
                            try {
                                duration = Integer.parseInt(media.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_DURATION));
                            }catch (Exception e){
                                e.printStackTrace();
                            }

                            File f = new File(urlpath);
                               /* File f = new File(Environment
                                        .getDownloadCacheDirectory().getPath()+ "/easyimVideo/", imgname);*/
                            if (f.exists()) {
                                f.delete();
                            }
                            try {
                                FileOutputStream out = new FileOutputStream(f);
                                bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
                                out.flush();
                                out.close();
                                //Log.i(TAG, "已经保存");
                                VedioEntity vedioEntity = new VedioEntity();
                                vedioEntity.setVedioPath(filePath);
                                vedioEntity.setVedioSize(duration);
                                vedioEntity.setVedioBitmappath(urlpath);
                                sendVedio(vedioEntity);
                            } catch (FileNotFoundException e) {
                                showToast(getResources().getString(R.string.sp_hetpath_fail));
                                e.printStackTrace();
                            } catch (IOException e) {
                                showToast(getResources().getString(R.string.sp_hetpath_fail));
                                e.printStackTrace();
                            }
                        }
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
//                break;
        }
    }

    private void sendVedio(final VedioEntity vedioEntity){

        final String vedioPath = vedioEntity.getVedioPath();
        final String vedioBitmappath = vedioEntity.getVedioBitmappath();

        new Thread(new Runnable() {
            @Override
            public void run() {
                String vedioimgurl = HttpAssist.uploadFile(new File(vedioBitmappath), "", false);//上传缩略图
                String vediourl = HttpAssist.uploadFile(new File(vedioPath), "", false);//上传视屏
                ImageEntity img1 = new Gson().fromJson(vedioimgurl, ImageEntity.class);
                ImageEntity img2 = new Gson().fromJson(vediourl, ImageEntity.class);
//                vedioEntity.setVedioUrl(img2.getData().getInfo().get(0));
//                vedioEntity.setGetVedioBitmapUrl(img1.getData().getInfo().get(0));
//                String vediocontent = new Gson().toJson(vedioEntity);
//                vedioMessage.setContent(vediocontent);
//                sendMessageHandler.sendEmptyMessage(VEDIO_FINISH);

                mvedioimgurl = img1.getData().getInfo().get(0);//缩略图
                mvediourl = img2.getData().getInfo().get(0) ;

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mGridView.setVisibility(View.GONE);
                        GlideUtils.loadImage(SendCircleActivity.this, vedioBitmappath, image_video);
                        relative_video.setVisibility(View.VISIBLE);
                    }
                });

            }
        }).start();
    }

    boolean isOkClick = false ;

    @Override
    protected void onResume() {
        super.onResume();
    }

    @OnClick({R.id.pre_v_back, R.id.ok, R.id.relative_address, R.id.relative_all, R.id.relative_at})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.pre_v_back:
                finish();
                break;
            case R.id.ok:
//                isSend = isSend + 1 ;
//                try {
//                    Thread.sleep(100);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
                if (isOkClick){
                    return;
                }else {
                    isOkClick = true ;
                    if (StringUtils.isEmpty(editText.getText().toString().trim()) && files.size() == 0) {

                        showToast(getResources().getString(R.string.send_content_nonull));
                        isSend = 0 ;
                    } else {

                        if (editText.getText().toString().trim().length() > 500){
                            showToast("发布的内容不能超过500");
                            return;
                        }

                        switch (type){
                            case 0 :
                                if (files.size() > 0) {
                                    showProgress(getResources().getString(R.string.commit_now), false);
                                    new Thread(new Runnable() {
                                        @Override
                                        public void run() {
                                            // Looper.loop();
                                            upload = HttpAssist.upload(files);
                                            StringBuffer sb = new StringBuffer("");
                                            if (upload == null) {
                                                Log.i("info", "图片上传失败");
                                                hideProgress();
                                                runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        showToast(getResources().getString(R.string.image_output_fail));

                                                    }
                                                });

                                            } else {
                                                List<String> info = upload.getData().getInfo();
                                                for (int q = 0; q < info.size(); q++) {
                                                    sb.append(info.get(q));
                                                    if (info.size() > 1 && q != info.size() - 1) {
                                                        sb.append(",");
                                                    }
                                                }
                                                sendCircle(sb.toString());
                                            }
                                        }
                                    }).start();
                                }else {
                                    sendCircle("");
                                }
                                break;
                            case 1 :
                                sendCircle("");
                                break;
                            case 2 :
                                if (mvedioimgurl.length() > 0 && mvediourl.length() > 0){
                                    sendCircle(mvedioimgurl);
                                }else {
                                    sendCircle("");
                                }
                                break;
                        }


                    }
                }


              /*
                if (null!=photoPath&& !StringUtils.isEmpty(photoPath)){
                    showProgress("正在提交");
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            String s = HttpAssist.uploadFile(new File(photoPath), "", false);
                            ImageEntity imageEntity = new Gson().fromJson(s,ImageEntity.class);
                            if (!StringUtils.isEmpty(s)){

                            }
                        }
                    }).start();
                }else {
                    showToast("您还没有选择图片");
                }*/

                break;

            case R.id.relative_address:
                startActivityForResult(LocationActivity.class, ChatActivity.RESULT_LOCATION);
                break;
            case R.id.relative_all:
                CircleLookWhoActivity.startActivity(SendCircleActivity.this);
                break;
            case R.id.relative_at:
                SelecteGroupFriendActivity.startActivity(SendCircleActivity.this,1,0);
                break;
        }
    }

    /**
     *  userid 自己uid
     * text 文字
     * images 图片链接  字符串，分开
     * address 地址
     * lat
     * lng
     * at   @好友 uid，分开
     * priv  隐私 0公开 1私密 2部分可见 3不给谁看
     * uids   部分可见  不给谁看  的好友uid
     * video  小视频链接
     * @param sb
     */
    private void sendCircle(String sb) {

        PGService.getInstance().postcircle(sb, ToolsUtils.getMyUserId(), editText.getText().toString(),addr,
                ""+lat,""+lut,uids,""+typeall, uidsall,mvediourl
                ).subscribe(new AbsAPICallback<SendCircleEntivity>() {
            @Override
            protected void onResultError(ApiException ex) {
                showToast(getResources().getString(R.string.send_faild));
                hideProgress();
                isSend = 0 ;
                isOkClick = false ;
            }

            @Override
            public void onNext(SendCircleEntivity sendCircleEntivity) {
                if (sendCircleEntivity != null) {
                    showToast(getResources().getString(R.string.send_success));
                    EventBus.getDefault().post("发布成功");
                    hideProgress();
//                    hideProgress();
                    finish();
                    isSend = 0 ;
                }
            }
        });
    }


   /* private void upload(List<String> lists){
        List<Observable> mObservables = new ArrayList<>();
        for (int i = 0; i < lists.size(); i++) {

            File mFile = new File(lists.get(i).toString());
            //压缩图片 并上传至服务器
            Observable<ValidateEntivity> mObservable = Luban.get(this).load(mFile)
                    .putGear(Luban.THIRD_GEAR)
                    .asObservable()
                    .flatMap(new Func1<File, Observable<ValidateEntivity>>() {
                        @Override
                        public Observable<ValidateEntivity> call(File mFile) {

                            RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), mFile);
                            // MultipartBody.Part is used to send also the actual file name
                            MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", mFile.getName(), requestFile);

                            return RetrofitHelper.getDefault().uploadImage(SyncStateContract.Constants.LAND_POSITION, filePart);
                        }
                    });

            mObservables.add(mObservable);

        }
        Observable.zip(mObservables, new FuncN<List<String>>() {
            @Override
            public List<String> call(Object... args) {
                for (Object m :
                        args) {
                    if (m != null) {
                        ValidateEntivity mbase = (ValidateEntivity) m;
                       // mImgs.add(mbase.data);
                    }
                }
                return mImgs;
            }
        })
                .flatMap(new Func1<List<String>, Observable<ValidateEntivity>>() {
                    @Override
                    public Observable<ValidateEntivity> call(List<String> mList) {
                        return RetrofitHelper.getDefault().addLand(mLand);
                    }
                })
                .compose(RxHelper.<String>handleResult())
                .subscribe(new DefaultSubscriber<String>(mContext) {
                    @Override
                    protected void _onNext(final String mS) {

                        showToast("添加成功");
                        mButtonSave.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mLand.id = mS;
                                Intent mIntent = new Intent();
                                mIntent.putExtra(DATA, mLand);
                                setResult(RESULT_OK, mIntent);
                                finish();
                            }
                        }, 1000);


                    }

                    @Override
                    protected void _onError(String message) {

                        showToast(message);

                    }
                });

    }
*/


}
